<template>
  <div class="app-container client-stage">
    <el-radio-group class="state-radio-group" v-model="stateRadio" @change="changeModel">
      <el-radio-button label="列表视图" value="list" />
      <el-radio-button label="内容视图" value="content" />
    </el-radio-group>
    <template v-if="stateRadio === 'list'">
      <el-table
        v-loading="isLoading"
        element-loading-text="数据加载中..."
        :data="stageList"
        stripe
        style="width: 100%"
        border
        :header-cell-style="{ background: '#F2F6FC', color: '#909399', 'font-weight': 400, 'font-size': '14px' }"
        :row-class-name="tableRowClassName"
      >
        <el-table-column prop="stageName" label="客户阶段" width="150" show-overflow-tooltip fixed />
        <el-table-column prop="taskName" label="任务名称" width="200" show-overflow-tooltip fixed />
        <el-table-column prop="userName" label="责任人" width="100"></el-table-column>
        <el-table-column label="是否必须">
          <template #default="{ row }">
            <span>{{ row.isMust ? "是" : "否" }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="executeDays" label="标准天数"></el-table-column>
        <el-table-column label="状态">
          <template #default="{ row }">
            <el-tag :type="getStageState(row.status)[1]">{{ getStageState(row.status)[0] }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="plainStartDate" label="计划开始日期" width="200"></el-table-column>
        <el-table-column prop="factStartDate" label="实际开始日期" width="200"></el-table-column>
        <el-table-column prop="plainEndDate" label="计划完成日期" width="200"></el-table-column>
        <el-table-column prop="factEndDate" label="实际完成日期" width="200"></el-table-column>
        <el-table-column label="操作" width="100" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handelCheckStage(row)">查看</el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>
    <template v-else>
      <div class="flex-overflow content-container" v-loading="isViewLoading" element-loading-text="数据加载中...">
        <template v-if="contentData.length">
          <div class="content-container-form" v-for="item in contentData">
            <h3>{{ formNameRender(item).value }}</h3>
            <FormRender :forms="renderFormsData(item).value" :config="formConfigData" v-model="item.data" />
          </div>
        </template>
        <template v-else>
          <el-empty />
        </template>
      </div>
    </template>

    <!--  流程任务待办 start  -->
    <div class="client-stage-drawer">
      <el-drawer v-model="isHandleDrawer" :with-header="false" :close-on-click-modal="false">
        <div class="stage-intention">
          <title-view :title="stageNameDrawer" />
          <div class="state-forms" v-loading="formRenderLoading" element-loading-text="数据加载中...">
            <template v-if="formItemsData.length">
              <FormRender ref="formRenderRef" :forms="formItemsData" v-model="formModelData" />
            </template>
            <template v-else>
              <el-empty />
            </template>
          </div>
          <div class="state-btns">
            <el-button style="width: 92px; background-color: #f2f3f5" size="default" @click="handelCloseDrawer">取消</el-button>
          </div>
        </div>
        <div class="stage-follow-up" v-loading="isStateFollowLoading" element-loading-text="数据加载中...">
          <title-view title="跟进内容" isClose @close="handelCloseDrawer" />
          <el-timeline style="max-width: 600px" :hollow="true">
            <template v-if="followUpData.length">
              <el-timeline-item v-for="item in followUpData">
                <div class="timeline-date">
                  <span class="date">{{ followDate(item.trackDatetime).value }}</span>
                  <span class="time">
                    <el-icon><Clock /></el-icon>
                    {{ followtime(item.trackDatetime).value }}
                  </span>
                </div>
                <div>
                  <div class="timeline-title">{{ item.trackTypeName }}</div>
                  <div class="timeline-desc">
                    <div class="timeline-desc-content">
                      {{ item.contentDesc }}
                    </div>
                    <div class="timeline-desc-images">
                      <el-image
                        :preview-src-list="[imgItem.url]"
                        v-for="imgItem in item.crmFileVOList"
                        :key="imgItem.url"
                        :src="imgItem.url"
                      ></el-image>
                    </div>
                    <div class="timeline-desc-name">{{ item.roleName }}</div>
                  </div>
                </div>
              </el-timeline-item>
            </template>
            <template v-else>
              <el-empty />
            </template>
          </el-timeline>
        </div>
      </el-drawer>
    </div>
    <!--  流程任务待办 end  -->

    <!-- 跟进任务待办 start-->
    <div class="client-follow-drawer">
      <el-drawer v-model="isFollowDrawer" :with-header="false" :close-on-click-modal="false" destroy-on-close>
        <div class="stage-follow-up" v-loading="isStateFollowLoading" element-loading-text="数据加载中...">
          <title-view title="跟进内容" isClose @close="handelCloseDrawer" />
          <el-timeline style="max-width: 600px" :hollow="true">
            <template v-if="followUpData.length">
              <el-timeline-item v-for="item in followUpData">
                <div class="timeline-date">
                  <span class="date">{{ followDate(item.trackDatetime).value }}</span>
                  <span class="time">
                    <el-icon><Clock /></el-icon>
                    {{ followtime(item.trackDatetime).value }}
                  </span>
                </div>
                <div>
                  <div class="timeline-title">{{ item.trackTypeName }}</div>
                  <div class="timeline-desc">
                    <div class="timeline-desc-content">
                      {{ item.contentDesc }}
                    </div>
                    <div class="timeline-desc-images">
                      <el-image
                        :preview-src-list="[imgItem.url]"
                        v-for="imgItem in item.crmFileVOList"
                        :key="imgItem.url"
                        :src="imgItem.url"
                      ></el-image>
                    </div>
                    <div class="timeline-desc-name">{{ item.roleName }}</div>
                  </div>
                </div>
              </el-timeline-item>
            </template>
            <el-empty v-else />
          </el-timeline>
          <!-- <div class="state-btns">
            <el-button @click="handelCloseDrawer" size="default">取消</el-button>
          </div> -->
        </div>
      </el-drawer>
    </div>
    <!-- 跟进任务待办 end-->
  </div>
</template>

<script setup>
import { ref } from "vue";
import { dayjs } from "element-plus";
import { tableRowClassName } from "@/views/loseClient/clientLose/utils";
import { Clock, Plus, QuestionFilled } from "@element-plus/icons-vue";
import { getStageList, getStageView as stageView, clientInfoAndFollow } from "@/apis/clientLose";
import useUserStore from "@/store/modules/user";
import useComputedParams from "@/hooks/useComputedParams";
import FormRender from "@/components/customComponents/formRender.vue";
import { dictList } from "@/apis/dict/dict";
import defaultConfig from "@/settings";
import { processInstanceForm, detailProcessModel, approvalForm } from "@/apis/workflow";

const props = defineProps({
  customerId: {
    type: String,
    default: ""
  }
});
const userStore = useUserStore();
const stateRadio = ref("list");
const stageStates = new Map([
  [2, ["进行中", "primary"]],
  [3, ["已完成", "success"]],
  [1, ["未开始", "info"]]
]);
const getStageState = state => {
  return stageStates.get(state) || ["数据错误", "danger"];
};

/**
 * 查看
 */
const formRenderLoading = ref(false);
const isStateFollowLoading = ref(false);
const isHandleDrawer = ref(false);
const isFollowDrawer = ref(false);
const fllowUpTypes = ref([]);
const followUpData = ref([]);
const defId = ref(""); // 表单defId
const formInstanceId = ref(""); // 表单实例id
const stageNameDrawer = ref("");

const isDisableFollowUp = ref(false);
// 表单模型
const formItemsData = ref([]);
const formModelData = ref({});
const formConfigData = ref({});
const getProcessModel = async () => {
  try {
    formRenderLoading.value = true;
    const { data = {} } = await detailProcessModel(defId.value);
    formItemsData.value = data?.formItems ? JSON.parse(data.formItems) : [];
    if (isDisableFollowUp.value) {
      formItemsData.value.forEach(item => {
        item.props.disabled = true;
      });
    }
    formInstanceId.value && getProcessInstanceForm();
    formRenderLoading.value = false;
  } catch (err) {
    formRenderLoading.value = false;
  }
};
// 表单模型——详情
const getAuditAndToDoData = async () => {
  try {
    formRenderLoading.value = true;
    const { data } = await approvalForm(formInstanceId.value);
    formRenderLoading.value = false;
    formConfigData.value = data?.formConfig ?? {};
    formItemsData.value = data?.formItems || [];
    if (isDisableFollowUp.value) {
      formItemsData.value.forEach(item => {
        item.props.disabled = true;
      });
    }
    formModelData.value = data?.formData || {};
  } catch (err) {
    formRenderLoading.value = false;
  }
};
// 表单实例模型
const getProcessInstanceForm = async () => {
  const { data = {} } = await processInstanceForm(formInstanceId.value);
  formModelData.value = data;
  console.log(data, "<<<<<表单实例模型");
};
const getFllowUpType = async () => {
  const { data = [] } = await dictList({ dictType: defaultConfig.dicts.FOLLER_UP_TYPE });
  console.log(data, "<<<<<跟进类型");
  fllowUpTypes.value = data;
};
const getClientInfoAndFollow = customerId => {
  isStateFollowLoading.value = true;
  clientInfoAndFollow(customerId)
    .then(res => {
      const crmCustomerTrackList = res.data?.crmCustomerTrackList || [];
      followUpData.value = crmCustomerTrackList.map(item => {
        item.roleName = `${item.roleName}  ${item.updateBy}提交于${item?.updateTime ? dayjs(item.updateTime).format("HH:mm") : ""}`;
        fllowUpTypes.value.some(subItem => {
          if (item.trackType === subItem.dictCode) {
            item.trackTypeName = subItem.dictLabel;
            return true;
          }
        });
        return item;
      });
      console.log("跟进详情>>>", res);
      isStateFollowLoading.value = false;
    })
    .catch(err => {
      console.log("跟进详情>>>", err);
      isStateFollowLoading.value = false;
    });
};
const followDate = useComputedParams(time => {
  return dayjs(time).format("YYYY-MM-DD");
});
const followtime = useComputedParams(time => {
  return dayjs(time).format("hh:mm:ss");
});
const handelCheckStage = data => {
  isDisableFollowUp.value = true;
  if (data.taskType === defaultConfig.taskTypeObj.FOLLOW_UP_TASK) {
    isFollowDrawer.value = true;
    getClientInfoAndFollow(data.customerId);
    return;
  }
  isHandleDrawer.value = true;
  defId.value = data.formId; // 表单defId
  formInstanceId.value = data.formInstanceId; // 表单实例id
  stageNameDrawer.value = data.stageName;
  getClientInfoAndFollow(data.customerId);
  formInstanceId.value && getAuditAndToDoData();
};
const handelCloseDrawer = () => {
  isHandleDrawer.value = false;
  isFollowDrawer.value = false;
  isDisableFollowUp.value = false;
  followUpData.value = [];
  formItemsData.value = [];
  formModelData.value = {};
};

/**
 * 客户阶段列表、内容视图
 */
const stageList = ref([]);
const contentData = ref([]);
const isLoading = ref(false);
const isViewLoading = ref(false);
const formNameRender = useComputedParams(item => {
  return item?.processModel?.formName || "";
});
const renderFormsData = useComputedParams(formItems => {
  if (formItems) {
    const itemsData = formItems?.processModel?.formItems ? JSON.parse(formItems.processModel.formItems) : [];
    return itemsData.map(item => {
      item.props.disabled = true;
      return item;
    });
  }
  return [];
});
const getStageListData = async () => {
  try {
    isLoading.value = true;
    const { data = [] } = await getStageList(props.customerId);
    const list = data?.length ? data : [];
    stageList.value = list.map(item => {
      return {
        ...item,
        plainStartDate: item.plainStartDate ? dayjs(item.plainStartDate).format("YYYY-MM-DD") : "",
        factStartDate: item.factStartDate ? dayjs(item.factStartDate).format("YYYY-MM-DD") : "",
        plainEndDate: item.plainEndDate ? dayjs(item.plainEndDate).format("YYYY-MM-DD") : "",
        factEndDate: item.factEndDate ? dayjs(item.factEndDate).format("YYYY-MM-DD") : ""
      };
    });
    isLoading.value = false;
  } catch (err) {
    isLoading.value = false;
    console.log(err, "<<<阶段列表");
  }
};
const getStageView = async () => {
  try {
    isViewLoading.value = true;
    const { data = [] } = await stageView(props.customerId);
    contentData.value = data;
    isViewLoading.value = false;
  } catch (err) {
    isViewLoading.value = false;
    console.log(err, "<<<内容视图");
  }
};

// 切换视图
const changeModel = val => {
  val === "list" && getStageListData();
  val === "content" && getStageView();
};

getStageListData();
getFllowUpType();
</script>

<style scoped lang="scss">
@use "clientStage";
</style>
